#import "IdImagePool.h"
#import "Config.h"

@implementation IdImagePool

static IdImagePool * instance;

@synthesize idIconImages, idDownloadQueue, delegate;

+ (IdImagePool *) sharedInstance {
	if (instance == nil) {
		instance = [[IdImagePool alloc] init];
	}
	
	return instance;
}

- (id)init {
	if (self = [super init]) {
		idIconImages = [[NSMutableDictionary alloc] init];
		idDownloadQueue = [[NSMutableArray alloc] init];
	}
	
	return self;
}

- (id)initFromFile: (NSString *)strFilename delegate:(id<IdImagePoolDelegate>)aDelegate {
	if (self = [super init]) {
		idIconImages = [[NSMutableDictionary alloc] init];
		idDownloadQueue = [[NSMutableArray alloc] init];
		
		delegate = aDelegate;
	}

	return self;
}

- (void)dealloc
{
	[idIconImages release];
	[idDownloadQueue release];
	[super dealloc];
}

/*!
	주어진 주소의 이미지를 자체 dictionary에서 찾아보고 없으면 download한다.
	@param idImageUrl 찾고자하는 이미지의 주소(http://clien.career.co.kr/cs2/data/member/ci/cipher.gif
	@return 주어진 주소의 이미지가 있으면 이미지를, 그렇지 않으면 nil을 돌려준다
*/
- (UIImage *)getIdImage: (NSString *)idImageUrl {
	UIImage *idImage = [idIconImages objectForKey:idImageUrl];

	if ( (idImage == nil) && ([idDownloadQueue indexOfObject:idImageUrl] == NSNotFound) ) {
		[idDownloadQueue addObject:idImageUrl];
		if ([idDownloadQueue count] == 1) {
			[NSThread detachNewThreadSelector:@selector(doDownload) toTarget:self withObject:nil];
		}
	}

	return idImage;
}

- (void)pushDownloadQueue:(NSString *)idImageUrl
{
	UIImage *idImage = [idIconImages objectForKey:idImageUrl];
	
	if ( (idImage == nil) && ([idDownloadQueue indexOfObject:idImageUrl] == NSNotFound) ) {
		[idDownloadQueue addObject:idImageUrl];
		//NSLog(@"Que %@", idImageUrl);
	}
}

- (void)startDownload {
	if ([idDownloadQueue count] > 0) {
		[NSThread detachNewThreadSelector:@selector(doDownload) toTarget:self withObject:nil];
	}
}

- (void)doDownload {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	NSString *idImageUrl;
	UIImage *idImage;
	NSMutableURLRequest *reqWithParams;
	NSData * imageData;

	while ([idDownloadQueue count] > 0)
	{
		idImageUrl = [idDownloadQueue objectAtIndex:0];

		reqWithParams = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:idImageUrl]];
		imageData = [NSURLConnection sendSynchronousRequest:reqWithParams returningResponse:nil error:nil];
		idImage = [UIImage imageWithData:imageData];

		[idIconImages setObject:idImage forKey:idImageUrl];
		[idDownloadQueue removeObjectAtIndex:0];
	}
	//[self.delegate downImageFinish:nil];
	[self performSelectorOnMainThread:@selector(UpdateIdIcon) withObject:nil waitUntilDone:YES];

	[pool release];
}

- (void)UpdateIdIcon {
	[self.delegate downImageFinish:nil];
}

@end
